<!-- src/views/product/spu/index.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import {
  Search,
  RefreshRight,
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import api from '@/utils/request.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDay, formatLoginTime } from '@/utils/date.js'
// 分页数据
const spuList = ref([])
const loading = ref(false)
const total = ref(0)

// 品牌选项列表 (key: 品牌ID, value: 品牌名称)
const brandList = ref({})

// 获取品牌列表
const getBrandList = async () => {
  try {
    const result = await api.get('tBrand/list') // 根据实际接口调整路径
    if (result.code === 200) {
      brandList.value = result.data
    }
  } catch (error) {
    ElMessage.error('获取品牌列表失败')
  }
}

// 级联选择器选项
const cascaderOptions = ref([])

// 级联选择器配置
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  emitPath: true, // 只返回选中节点的值，而不是完整路径
  checkStrictly: true // 可以选择任意一级节点
}

// 转换类型数据为级联选择器格式
const transformCategoryData = (data) => {
  if (!Array.isArray(data)) return []

  return data.map(item => {
    const option = {
      id: item.id,
      name: item.name
    }

    if (item.children && item.children.length > 0) {
      option.children = item.children.map(child => ({
        id: child.id,
        name: child.name
      }))
    }

    return option
  })
}

// 修改 getTypeList 方法
const getTypeList = async () => {
  try {
    const result = await api.get('/tCategory/list1')
    if (result.code === 200) {
      cascaderOptions.value = transformCategoryData(result.data)
    }
  } catch (error) {
    ElMessage.error('获取类型列表失败')
  }
}

//搜索时间范围
const searchTime = ref(["",""])

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  Name: '',     // 商品名称查询条件
  brandId: '',     // 品牌ID查询条件
  categoryId: '',  // 分类ID查询条件
  secondCategoryId: '', // 二级分类ID查询条件
  status: '',      // 状态查询条件
  startTime: '',   // 开始时间
  endTime: ''      // 结束时间
})

// 重置查询条件
const resetQueryForm = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    spuName: '',     // 商品名称查询条件
    brandId: '',     // 品牌ID查询条件
    categoryId: '',  // 一级分类ID查询条件
    secondCategoryId: '', // 二级分类ID查询条件
    status: '',      // 状态查询条件
    startTime: '',
    endTime: ''
  }
  searchTime.value = ["",""]
  getSpuList()
}

let query = ()=>{
  if (searchTime.value[0] !== ''){
    queryParams.value.startTime = formatLoginTime(searchTime.value[0])
    queryParams.value.endTime = formatLoginTime(searchTime.value[1])
  }

  // 处理级联选择器的值
  if (Array.isArray(queryParams.value.categoryId)) {
    if (queryParams.value.categoryId.length === 1) {
      queryParams.value.categoryId = queryParams.value.categoryId[0]
      queryParams.value.secondCategoryId = ''
    } else if (queryParams.value.categoryId.length === 2) {
      // 先保存原始值再处理
      const categoryIdArray = [...queryParams.value.categoryId];
      queryParams.value.categoryId = categoryIdArray[0];
      queryParams.value.secondCategoryId = categoryIdArray[1];
    } else {
      queryParams.value.categoryId = ''
      queryParams.value.secondCategoryId = ''
    }
  }

  api.get('/tSpu/info', queryParams.value).then(result => {
    spuList.value = result.data.list
    total.value = result.data.total
  })
}

const getSpuList = async () => {
  loading.value = true
  try {
    const result = await api.get('/tSpu/Tspage', {
          pageNum: queryParams.value.pageNum,
          pageSize: queryParams.value.pageSize
        }
    )
    spuList.value = result.data.list
    total.value = result.data.total
  } catch (error) {
    ElMessage.error('请求失败')
  } finally {
    loading.value = false
  }
}

// 分页相关方法
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  queryParams.value.pageNum = 1
  getSpuList()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getSpuList()
}

// 操作方法
// 添加对话框相关
const addDialogVisible = ref(false)
// 添加对话框相关
const addForm = ref({
  spuName: '',
  brandId: '',
  categoryId: '',  // 一级分类ID
  secondCategoryId: '', // 二级分类ID
  categoryName: '', // 一级分类名称
  secondCategoryName: '', // 二级分类名称
  spuMoney:'',
  unit: '',
  status: '1',
  detailHtml: ''
})

// 添加表单验证规则
const addFormRules = {
  spuName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  brandId: [
    { required: true, message: '请选择品牌', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请输入计量单位', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 添加商品
const handleAdd = () => {
  addDialogVisible.value = true
  // 重置表单
  addForm.value = {
    spuName: '',
    brandId: '',
    categoryId: '',  // 一级分类ID
    secondCategoryId: '', // 二级分类ID
    categoryName: '', // 一级分类名称
    secondCategoryName: '', // 二级分类名称
    unit: '',
    spuMoney:'',
    status: '1',
    detailHtml: ''
  }
}

// 提交添加 - 修改数据处理部分
const submitAdd = async () => {
  try {
    // 处理分类数据
    const formData = { ...addForm.value }

    // 处理级联选择器的值
    if (Array.isArray(formData.categoryId)) {
      if (formData.categoryId.length === 1) {
        // 只选择了一级分类
        formData.categoryId = formData.categoryId[0]
        formData.categoryName = getCascaderLabel(formData.categoryId)
        formData.secondCategoryId = ''
        formData.secondCategoryName = ''
      } else if (formData.categoryId.length === 2) {
        // 选择了一级和二级分类
        const categoryIdPath = [...formData.categoryId]
        formData.categoryId = categoryIdPath[0]
        formData.secondCategoryId = categoryIdPath[1]
        formData.categoryName = getCascaderLabel(categoryIdPath[0])
        formData.secondCategoryName = getCascaderLabel(categoryIdPath[1])
      } else {
        formData.categoryId = ''
        formData.categoryName = ''
        formData.secondCategoryId = ''
        formData.secondCategoryName = ''
      }
    }

    const result = await api.postJson('/tSpu/add', formData)
    if (result.code === 200) {
      ElMessage.success('添加成功')
      addDialogVisible.value = false
      getSpuList() // 重新加载列表
    } else {
      ElMessage.error(result.msg || '添加失败')
    }
  } catch (error) {
    ElMessage.error('添加失败')
  }
}


// 取消添加
const cancelAdd = () => {
  addDialogVisible.value = false
}

// 编辑对话框相关
const editDialogVisible = ref(false)
// 编辑对话框相关
const editForm = ref({
  id: '',
  spuNo: '',
  spuName: '',
  brandId: '',
  categoryId: '',  // 一级分类ID
  secondCategoryId: '', // 二级分类ID
  categoryName: '', // 一级分类名称
  secondCategoryName: '', // 二级分类名称
  unit: '',
  spuMoney:'',
  status: '1',
  detailHtml: ''
})

// 编辑表单验证规则（可复用添加表单规则或单独定义）
const editFormRules = {
  spuName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  brandId: [
    { required: true, message: '请选择品牌', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请输入计量单位', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 编辑商品
const handleEdit = (row) => {
  editDialogVisible.value = true
  // 填充表单数据
  editForm.value = {
    id: row.id,
    spuNo: row.spuNo,
    spuName: row.spuName,
    brandId: row.brandId,
    categoryId: row.categoryId,
    secondCategoryId: row.secondCategoryId || '',
    unit: row.unit,
    spuMoney:row.spuMoney,
    status: row.status ? row.status.toString() : '1',
    detailHtml: row.detailHtml || ''
  }
}

// 提交编辑
const submitEdit = async () => {
  try {
    // 处理分类数据
    const formData = { ...editForm.value }

    // 处理级联选择器的值
    if (Array.isArray(formData.categoryId)) {
      if (formData.categoryId.length === 1) {
        formData.categoryId = formData.categoryId[0]
        formData.secondCategoryId = ''
      } else if (formData.categoryId.length === 2) {
        // 先保存原始值再处理
        const categoryIdArray = [...formData.categoryId];
        formData.categoryId = categoryIdArray[0];
        formData.secondCategoryId = categoryIdArray[1];
      } else {
        formData.categoryId = ''
        formData.secondCategoryId = ''
      }
    }

    const result = await api.putJson('/tSpu/update', formData)
    if (result.code === 200) {
      ElMessage.success('编辑成功')
      editDialogVisible.value = false
      getSpuList() // 重新加载列表
    } else {
      ElMessage.error(result.msg || '编辑失败')
    }
  } catch (error) {
    ElMessage.error('编辑失败')
  }
}

// 获取级联选择器节点标签的辅助函数
const getCascaderLabel = (targetId) => {
  if (!targetId || !cascaderOptions.value) return ''

  const findLabel = (nodes) => {
    for (const node of nodes) {
      if (node.id === targetId) {
        return node.name
      }
      if (node.children) {
        const found = findLabel(node.children)
        if (found) return found
      }
    }
    return ''
  }

  // 添加计算完整类目名称的函数
  const getCategoryFullName = (row) => {
    if (row.categoryName && row.secondCategoryName) {
      return `${row.categoryName}/${row.secondCategoryName}`
    } else if (row.categoryName) {
      return row.categoryName
    } else if (row.secondCategoryName) {
      return row.secondCategoryName
    }
    return ''
  }

  return findLabel(cascaderOptions.value)
}


// 取消编辑
const cancelEdit = () => {
  editDialogVisible.value = false
}

// 批量删除相关
const selectedRows = ref([]) // 存储选中的行数据

// 表格选择事件处理
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据')
    return
  }

  const ids = selectedRows.value.map(row => row.id)
  ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}条商品数据吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const result = await api.postJson('/tSpu/delete', ids)
      if (result.code === 200) {
        ElMessage.success('删除成功')
        getSpuList() // 重新加载列表
      } else {
        ElMessage.error(result.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除商品"${row.spuName}"吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const result = await api.postJson('/tSpu/delete', [row.id])
      if (result.code === 200) {
        ElMessage.success('删除成功')
        getSpuList()
      } else {
        ElMessage.error(result.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除请求失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '网络错误'))
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 初始化
onMounted(() => {
  getBrandList()
  getSpuList()
  getTypeList()
})
</script>

<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-row>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="编号/商品名">
          <el-input v-model="queryParams.name"  clearable />
        </el-form-item>
        <el-form-item label="品牌">
          <el-select
              v-model="queryParams.brandId"
              placeholder="请选择品牌"
              clearable
          >
            <el-option
                v-for="(brandName, brandId) in brandList"
                :key="brandId"
                :label="brandName"
                :value="brandId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-cascader
              v-model="queryParams.categoryId"
              :options="cascaderOptions"
              :props="cascaderProps"
              placeholder="请选择类型"
              clearable
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
              v-model="queryParams.status"
              placeholder="状态"
              clearable
          >
            <el-option label="在售" value="1" />
            <el-option label="下架" value="2" />
            <el-option label="预售" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="searchTime"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
          />
        </el-form-item>
        <el-form-item >
          <el-button type="primary" :icon="Search" @click="query">查询</el-button>
          <el-button type="primary" :icon="RefreshRight" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 操作按钮 -->
    <el-row class="mb-10">
      <el-col>
        <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button
            type="danger"
            :icon="Delete"
            @click="handleBatchDelete"
            :disabled="selectedRows.length === 0"
        >
          批量删除
        </el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-row>
      <el-table
          v-loading="loading"
          :data="spuList"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="spuNo" label="商品编号" width="120" />
        <el-table-column prop="spuName" label="商品名称" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="类型" width="100" />
        <el-table-column prop="brandName" label="品牌" width="100" />
        <el-table-column prop="unit" label="计量单位" width="100" />
        <el-table-column prop="spuMoney" label="价格(元)" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">在售</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="warning">下架</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="info">预售</el-tag>
            <span v-else>{{ scope.row.status }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDay(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedTime" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDay(scope.row.updatedTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <!-- 分页 -->
    <el-row>
      <el-col :span="24">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>
  </div>

  <!-- 添加商品信息对话框 -->
  <el-dialog v-model="addDialogVisible" title="添加商品" width="600px" append-to-body>
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品名称" prop="spuName">
            <el-input v-model="addForm.spuName" placeholder="请输入商品名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="品牌" prop="brandId">
            <el-select v-model="addForm.brandId" placeholder="请选择品牌" clearable>
              <el-option
                  v-for="(brandName, brandId) in brandList"
                  :key="brandId"
                  :label="brandName"
                  :value="brandId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型" prop="categoryId">
            <el-cascader
                v-model="addForm.categoryId"
                :options="cascaderOptions"
                :props="cascaderProps"
                placeholder="请选择类型"
                clearable
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计量单位" prop="unit">
            <el-input v-model="addForm.unit" placeholder="请输入计量单位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="价格" prop="unit">
            <el-input v-model="addForm.spuMoney" placeholder="请输入商品价格(元)" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="addForm.status" placeholder="请选择状态">
              <el-option label="在售" value="1" />
              <el-option label="下架" value="2" />
              <el-option label="预售" value="3" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品价格" prop="spuMoney">
            <el-input v-model="addForm.spuMoney" placeholder="请输入商品价格(元)" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="商品详情" prop="detailHtml">
            <el-input
                v-model="addForm.detailHtml"
                type="textarea"
                placeholder="请输入商品详情"
                :rows="4"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="submitAdd">确 定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑商品信息对话框 -->
  <el-dialog v-model="editDialogVisible" title="编辑商品" width="600px" append-to-body>
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="商品编号">
            <el-input v-model="editForm.spuNo" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品名称" prop="spuName">
            <el-input v-model="editForm.spuName" placeholder="请输入商品名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品价格" prop="spuName">
            <el-input v-model="editForm.spuMoney" placeholder="请输入商品价格(元)" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="品牌" prop="brandId">
            <el-select v-model="editForm.brandId" placeholder="请选择品牌" clearable>
              <el-option
                  v-for="(brandName, brandId) in brandList"
                  :key="brandId"
                  :label="brandName"
                  :value="brandId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型" prop="categoryId">
            <el-cascader
                v-model="editForm.categoryId"
                :options="cascaderOptions"
                :props="cascaderProps"
                placeholder="请选择类型"
                clearable
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计量单位" prop="unit">
            <el-input v-model="editForm.unit" placeholder="请输入计量单位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="editForm.status" placeholder="请选择状态">
              <el-option label="在售" value="1" />
              <el-option label="下架" value="2" />
              <el-option label="预售" value="3" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="商品详情" prop="detailHtml">
            <el-input
                v-model="editForm.detailHtml"
                type="textarea"
                placeholder="请输入商品详情"
                :rows="4"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
.mb-10 {
  margin-bottom: 10px;
}
</style>
